#pragma once
#include "dbng.hpp"
#include "../../DB/DBManager.h"
#include "../Common/Common.h"

#include "include\wrapper\cef_message_router.h"
#include "include/cef_parser.h"
#include "iguana\json.hpp"

#include <string>
#include <vector>
#include <memory>
#include <map>
using namespace std;
using namespace ormpp;

struct User{
    int id;
    string name;
    string position;
    string passwd;
    int departmentid;
    int roleid;
    string phone;
    string mail;
};
REFLECTION(User, id, name, position, passwd, departmentid, roleid, phone, mail)

class UserManager:public CefRefCount
{
private:
    static CefRefPtr<UserManager> user;
public:
    UserManager(){}
    ~UserManager(){}

    static bool process(string action, CefRefPtr<CefDictionaryValue> data,CefRefPtr<CefBrowser> browser,
        CefRefPtr<CefMessageRouterBrowserSide::Callback> callback){
        if(action == "login"){
            if(user->login(data->GetString("name"),data->GetString("passwd"))){
                callback->Success("{}");
            }else
                callback->Failure(404,"no user");
        }else if(action == "add"){
            User user=CefDictionary2Struct<User>(data);
            DBManager::inst()->insert(user);
            callback->Success("{}");
        }else if(action == "query"){
            iguana::string_stream ss;
            vector<User> item = DBManager::inst()->query<User>();
            for(auto it : item) it.passwd = "";
            iguana::json::to_json(ss, item);
            callback->Success(ss.str());
        }else if(action == "cancel"){
            browser->GetHost()->TryCloseBrowser();
        }
        return false;
    }
    bool login(string name,string passwd){
        vector<User> item = DBManager::inst()->query<User>("name='"+name+"' and passwd='"+passwd+"'");
        if(item.size() >0)
            return true;
        else 
            return false;
    }
};
